# -*-encoding: utf-8 -*-

import os, sys
from PIL import Image

class ImageUtil:
    #def __init__(self):
    #    pass
    
    @staticmethod
    def make_thumb(path, thumb_path, size, input_quality):
        #path是路径
        try:
            img = Image.open(path)
        except Exception, e:
            print e
            return
        width = int(img.size[0])
        height = int(img.size[1])
        box = ()
        if (width > height):
            delta = (width - height) / 2
            #box = (delta, 0, width - delta,  height)
            box = (delta, 0, height,  height)
        else:
            delta = (height - width) / 2
            #box = (0, delta, width, height - delta)
            box = (0, delta, width, width)
        region = img.crop(box)
        thumb = region.resize((size, size), Image.ANTIALIAS)

        mode = thumb.mode
        if mode not in ('L', 'RGB'):
            if mode not in ('L', 'RGB'):
                # 透明图片需要加白色底
                alpha = thumb.split()[3]
                bgmask = alpha.point(lambda x: 255-x)
                thumb = thumb.convert('RGB')
                thumb.paste((255,255,255), None, bgmask)
            else:
                thumb = thumb.convert('RGB')

        folderName = thumb_path[0: thumb_path.rfind('/') + 1]
        if not os.path.exists(folderName):
            os.makedirs(folderName)
        #thumb.save(thumb_path.replace('jpg', 'png'), quality = input_quality)
        thumb.save(thumb_path, quality = input_quality)
